package it.uai.domainsMigrator;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class MailSender {
	
	private static final Logger logger = Logger.getLogger(MailSender.class);
	private Properties props;
	private Session mailSession;

	public MailSender(String smtpHost, String smtpPort, String smtpUsername, String smtpPassword) {

		Authenticator auth = new SMTPAuthenticator(smtpUsername, smtpPassword);
		setProperties(smtpHost, smtpPort);		
		mailSession = Session.getDefaultInstance(props, auth);

	}

	private void setProperties(String smtpHost, String smtpPort) {
		props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", smtpHost);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", smtpPort);
		props.put("mail.smtp.starttls.enable", "true");
	}

	public void send(String sender, String recipient, String subject, String content) throws AddressException, MessagingException {

		
		mailSession.setDebug(true);
		
		Transport transport = mailSession.getTransport();
		MimeMessage message = new MimeMessage(mailSession);
		message.setContent(content, "text/plain");
		message.setSubject(subject);
		message.setFrom(new InternetAddress(sender));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
		
		logger.trace("Messaggio creato");
		
		transport.connect();
		
		logger.trace("Connessione effettuata, invio in corso");
		
		transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
		transport.close();
		
		logger.trace("Messaggio inviato");

	}

}
